﻿using CefSharp.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DidaManager.Native.Network
{
    public class NetworkConfigUrl
    {
        public string? login { get; set; }            // 登录
        public string? gw_lists { get; set; }         // 网关列表
        public string? gw_devs { get; set; }          // 网关设备列表
        public string? find_pw { get; set; }          // 找回密码
        public string? register_account { get; set; } // 注册账号
        public string? gw_info { get; set; }          // 网关信息
        public string? download { get; set; }         // 下载
        public string? fireware { get; set; }         // 固件
        public string? connect { get; set; }          // 连接
        public string? update { get; set; }           // 更新
        public string? moduleChunkUpdate { get; set; } // 模块分块更新
        public string? restart { get; set; }          // 重启
        public string? testVariable { get; set; }     // 测试变量
        public string? remote_get_sn { get; set; }    // 远程获取SN
        public string? remote_restart { get; set; }   // 远程重启
        public string? remote_reset { get; set; }     // 远程重置
        public string? remote_start { get; set; }     // 远程启动
        public string? remote_stop { get; set; }      // 远程停止
        public string? remote_status { get; set; }    // 远程状态
        public string? update_cloud { get; set; }     // 更新云
        public string? remote_dev_history_files { get; set; }                 // 远程设备历史文件
        public string? remote_dev_history_download { get; set; }              // 远程设备历史文件下载
        public string? remote_dev_history_del { get; set; }                   // 远程设备历史文件删除
        public string? remote_dev_history_stat { get; set; }                  // 远程设备历史文件状态
        public string? remote_dev_history_currentDate { get; set; }           // 远程设备历史文件当前日期
        public string? remote_dev_history_memory { get; set; }                // 远程设备历史文件内存
        public string? remote_upload_file { get; set; }                       // 远程上传文件
        public string? get_alicloudinfo { get; set; }                         // 获取阿里云信息
        public string? get_alicloudinfo_create { get; set; }                  // 创建阿里云信息
        public string? get_alicloudinfo_delete { get; set; }                  // 删除阿里云信息
        public string? get_alicloudinfo_update { get; set; }                  // 更新阿里云信息
        public string? remote_trans_productList { get; set; }                 // 远程透传获取全部产品列表
        public string? remote_trans_productPage { get; set; }                 // 远程透传分页获取产品列表
        public string? remote_trans_deviceList { get; set; }                  // 远程透传分页获取设备列表
        public string? remote_trans_deviceConfigs { get; set; }               // 远程透传获取设备配置链接
        public string? remote_trans_deviceConfigs_ { get; set; }              // 远程透传获取带屏网关配置链接
        public string? remote_trans_allProductList { get; set; }              // 远程透传获取产品端口列表    
        public string? remote_trans_token { get; set; }                       // 远程透传token
        public string? remote_trans_clientId { get; set; }                    // 远程透传clientId
        public string? remote_trans_cacheClear { get; set; }                  // 远程透传缓存清除
        public string? remote_trans_address { get; set; }                     // 远程透传地址
        public string? remote_trans_port { get; set; }                        // 远程透传端口
        public string? help_doc { get; set; }                                 // 帮助文档
        public string? learning_platform { get; set; }                        // 学习平台
        public string? api_doc { get; set; }                                  // API文档
        public string? quick_start { get; set; }                              // 快速开始
        public string? online_support { get; set; }                           // 在线支持

        public NetworkConfigUrl()
        {
        }

        public void Init()
        {
            try
            {
                var configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config", "urlconfig.json");
                if (!File.Exists(configPath))
                {
                    InitDefault();
                    return;
                }
                var jsonString = File.ReadAllText(configPath);
                var jObject = JObject.Parse(jsonString);

                // // 获取config对象
                JObject? networkConfig = null;
                if (jObject.TryGetValue("url", out var configToken))
                {
                    networkConfig = configToken as JObject;
                }

                if (networkConfig == null)
                {
                    return;
                }

                NetworkConfigUrl url = networkConfig.ToObject<NetworkConfigUrl>() ?? new NetworkConfigUrl();
                // this只读，不能赋值，所以需要使用反射
                var properties = this.GetType().GetProperties();
                foreach (var property in properties)
                {
                    property.SetValue(this, property.GetValue(url));
                }
            }
            catch (Exception ex)
            {
                InitDefault();
                Console.WriteLine($"初始化网络配置失败: {ex.Message}");
            }
        }

        public void InitDefault()
        {
            login = "https://www.didalink.com/api/app/user/login";
            gw_lists = "https://www.didalink.com/api/app/product/filterList";
            gw_devs = "https://www.didalink.com/api/app/devices/ByProductKey";
            find_pw = "https://www.baidu.com/";
            register_account = "https://www.baidu.com/";
            gw_info = "https://www.didalink.com/api/alicloudinfo/";
            download = "/v1/configUpdate";
            fireware = "/v1/moduleUpdate";
            connect = "/v1/checkConnect";
            update = "/v1/checkUpdate";
            moduleChunkUpdate = "/v1/moduleChunkUpdate";
            restart = "/v1/restart";
            testVariable = "/v1/testVariable";
            remote_get_sn = "/v1/hsk/getSN";
            remote_restart = "/v1/hsk/restart";
            remote_reset = "/v1/hsk/reset";
            remote_start = "/v1/hsk/start";
            remote_stop = "/v1/hsk/stop";
            remote_status = "/v1/hsk/status";
            update_cloud = "https://www.didalink.com/api/sync/data";
            remote_dev_history_files = "/v1/localStorage/getDatabase";
            remote_dev_history_download = "/v1/localStorage/download/";
            remote_dev_history_del = "/v1/localStorage/deleteFile";
            remote_dev_history_stat = "/v1/localStorage/checkStatus";
            remote_dev_history_currentDate = "/v1/localStorage/currentDate";
            remote_dev_history_memory = "/v1/localStorage/memory";
            remote_upload_file = "https://www.didalink.com/api/file/uploadAndDeleteOld";
            get_alicloudinfo = "https://www.didalink.com/api/alicloudinfo/all/";
            get_alicloudinfo_create = "https://www.didalink.com/api/alicloudinfo/create";
            get_alicloudinfo_delete = "https://www.didalink.com/api/alicloudinfo/del/";
            get_alicloudinfo_update = "https://www.didalink.com/api/alicloudinfo/update";
            remote_trans_productList = "http://emqx.didalink.com/api/emqxproduct/listByUserId";
            remote_trans_productPage = "https://www.didalink.com/mqtt/product/page";
            remote_trans_deviceList = "http://emqx.didalink.com/api/emqxdevice/listByProductId/";
            remote_trans_deviceConfigs = "http://emqx.didalink.com/api/emqxdevice/configLink/";          
            remote_trans_allProductList = "http://emqx.didalink.com/api/emqxproduct/allProductData/"; 
            remote_trans_token = string.Empty;                       
            remote_trans_clientId = string.Empty;                    
            remote_trans_cacheClear = string.Empty;    
            remote_trans_address = "8.129.167.93";
            remote_trans_port = "7004";
            help_doc = "https://www.didalink.com/help/doc";
            learning_platform = "https://www.didalink.com/learning/platform";
            api_doc = "https://www.didalink.com/api/doc";
            quick_start = "https://www.didalink.com/quick/start";
            online_support = "https://www.didalink.com/online/support";
        }
    }

    public class NetworkConfig
    {
        private static readonly Lazy<NetworkConfig> _instance = new Lazy<NetworkConfig>(() => new NetworkConfig());
        private NetworkConfigUrl _myUrl;
        private string fileName = "token.ini";
        private string section = "RemoteTrans";
        private string tokenKey = "Token";
        private string configDir = "config";
        
        private NetworkConfig()
        {
            _myUrl = new NetworkConfigUrl();
            _myUrl.Init();
        }
        
        public static NetworkConfig Instance => _instance.Value;
        
        public NetworkConfigUrl MyUrl => _myUrl;
        
        // 提供便捷的URL访问方法，避免空引用
        public string GetLoginUrl() => _myUrl.login ?? string.Empty;
        public string GetGwListsUrl() => _myUrl.gw_lists ?? string.Empty;
        public string GetGwDevsUrl() => _myUrl.gw_devs ?? string.Empty;
        public string GetFindPwUrl() => _myUrl.find_pw ?? string.Empty;
        public string GetRegisterAccountUrl() => _myUrl.register_account ?? string.Empty;
        public string GetGwInfoUrl() => _myUrl.gw_info ?? string.Empty;
        public string GetDownloadUrl() => _myUrl.download ?? string.Empty;
        public string GetFirewareUrl() => _myUrl.fireware ?? string.Empty;
        public string GetConnectUrl() => _myUrl.connect ?? string.Empty;
        public string GetUpdateUrl() => _myUrl.update ?? string.Empty;
        public string GetModuleChunkUpdateUrl() => _myUrl.moduleChunkUpdate ?? string.Empty;
        public string GetRestartUrl() => _myUrl.restart ?? string.Empty;
        public string GetTestVariableUrl() => _myUrl.testVariable ?? string.Empty;
        public string GetRemoteGetSnUrl() => _myUrl.remote_get_sn ?? string.Empty;
        public string GetRemoteRestartUrl() => _myUrl.remote_restart ?? string.Empty;
        public string GetRemoteResetUrl() => _myUrl.remote_reset ?? string.Empty;
        public string GetRemoteStartUrl() => _myUrl.remote_start ?? string.Empty;
        public string GetRemoteStopUrl() => _myUrl.remote_stop ?? string.Empty;
        public string GetRemoteStatusUrl() => _myUrl.remote_status ?? string.Empty;
        public string GetUpdateCloudUrl() => _myUrl.update_cloud ?? string.Empty;
        public string GetRemoteDevHistoryFilesUrl() => _myUrl.remote_dev_history_files ?? string.Empty;
        public string GetRemoteDevHistoryDownloadUrl() => _myUrl.remote_dev_history_download ?? string.Empty;
        public string GetRemoteDevHistoryDelUrl() => _myUrl.remote_dev_history_del ?? string.Empty;
        public string GetRemoteDevHistoryStatUrl() => _myUrl.remote_dev_history_stat ?? string.Empty;
        public string GetRemoteDevHistoryCurrentDateUrl() => _myUrl.remote_dev_history_currentDate ?? string.Empty;
        public string GetRemoteDevHistoryMemoryUrl() => _myUrl.remote_dev_history_memory ?? string.Empty;
        public string GetRemoteUploadFileUrl() => _myUrl.remote_upload_file ?? string.Empty;
        public string GetAlicloudInfoUrl() => _myUrl.get_alicloudinfo ?? string.Empty;
        public string GetAlicloudInfoCreateUrl() => _myUrl.get_alicloudinfo_create ?? string.Empty;
        public string GetAlicloudInfoDeleteUrl() => _myUrl.get_alicloudinfo_delete ?? string.Empty;
        public string GetAlicloudInfoUpdateUrl() => _myUrl.get_alicloudinfo_update ?? string.Empty;
        public string GetRemoteTransProductListUrl() => _myUrl.remote_trans_productList ?? string.Empty;
        public string GetRemoteTransProductPageUrl() => _myUrl.remote_trans_productPage ?? string.Empty;
        public string GetRemoteTransDeviceListUrl() => _myUrl.remote_trans_deviceList ?? string.Empty;
        public string GetRemoteTransDeviceConfigsUrl() => _myUrl.remote_trans_deviceConfigs ?? string.Empty;
        public string GetRemoteTransAllProductListUrl() => _myUrl.remote_trans_allProductList ?? string.Empty;
        public string GetRemoteTransClientId() => _myUrl.remote_trans_clientId ?? string.Empty;
        public string GetRemoteTransCacheClear() => _myUrl.remote_trans_cacheClear ?? string.Empty;
        public string GetRemoteTransAddress() => _myUrl.remote_trans_address ?? string.Empty;
        public string GetRemoteTransPort() => _myUrl.remote_trans_port ?? string.Empty;

        public string GetHelpDocUrl() => _myUrl.help_doc ?? string.Empty;
        public string GetLearningPlatformUrl() => _myUrl.learning_platform ?? string.Empty;
        public string GetApiDocUrl() => _myUrl.api_doc ?? string.Empty;
        public string GetQuickStartUrl() => _myUrl.quick_start ?? string.Empty;
        public string GetOnlineSupportUrl() => _myUrl.online_support ?? string.Empty;

        public string GetRemoteTransToken()
        {
            // 如果内存中的token为空，尝试从INI文件读取
            if (string.IsNullOrEmpty(_myUrl.remote_trans_token))
            {
                var iniHelper = new IniFileHelper(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, configDir, fileName));
                var tokenFromFile = iniHelper.ReadValue(section, tokenKey, "");
                if (!string.IsNullOrEmpty(tokenFromFile))
                {
                    _myUrl.remote_trans_token = tokenFromFile;
                }
            }
            return _myUrl.remote_trans_token ?? string.Empty;
        }

        public void SetRemoteTransToken(string token)
        {
            _myUrl.remote_trans_token = token;
            
            // 同时保存到INI文件
            if (!string.IsNullOrEmpty(token))
            {
                var iniHelper = new IniFileHelper(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, configDir, fileName));
                iniHelper.WriteValue(section, tokenKey, token);
            }
        }
        public void SetRemoteTransClientId(string clientId)
        {
            _myUrl.remote_trans_clientId = clientId;
        }

    }
}
